package team.chuangshu.lm.controller;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.models.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import team.chuangshu.lm.base.KeyUtil;
import team.chuangshu.lm.base.ResultUtil;
import team.chuangshu.lm.base.dto.ResultDTO;
import team.chuangshu.lm.base.page.PageList;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import team.chuangshu.lm.base.page.Paginator;
import team.chuangshu.lm.dto.MessageDTO;
import team.chuangshu.lm.entity.*;
import team.chuangshu.lm.service.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.IntStream;



/**
 *
 * @author Zhang
 * @since 2019-04-16
 */
@RestController
@RequestMapping("/message")
@Slf4j
public class MessageController {

    @Value("${serverIp}")
    private String serverIp;

    @Autowired
    public MessageService messageService;

    @Autowired
    public TeacherService teacherService;

    @Autowired
    public ClazzService clazzService;

    @Autowired
    public StudentService studentService;

    @Autowired
    public FacultyService facultyService;



    //@ResponseBody
    //@RequestMapping(value = "/insertMessage", method = RequestMethod.POST,produces = "text/html;charset=utf-8")
    @PostMapping(value = "/insertMessage")
    @ApiOperation(value = "学生申请请假")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "teacherId",value = "对应的老师的教工号",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "studentId",value = "学号",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "studentName",value = "学生姓名",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "beginTime",value = "请假开始时间,YYYY-MM-DD HH:MM 的格式",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "endTime",value = "请假结束时间",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "phone",value = "学生联系方式",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "reason",value = "请假理由",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "clazzNum",value = "请假节数",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "creatTime",value = "请假时间,时间格式同上，取当前时间",required = false,dataType = "Date"),
            @ApiImplicitParam(paramType = "query",name = "isLongtime",value = "长假标识，默认为0，请假时间超过3天改为1",required = true,defaultValue = "0",dataType = "Integer"),
            @ApiImplicitParam(paramType = "query",name = "levelOneSign",value = "默认为0", required = true,defaultValue = "0",dataType = "Integer"),
            @ApiImplicitParam(paramType = "query",name = "levelTwoSign",value = "默认为0", required = true,defaultValue = "0",dataType = "Integer"),
            @ApiImplicitParam(paramType = "query",name = "status",value = "假条状态，默认0",required = true,defaultValue = "0",dataType = "Integer"),
            @ApiImplicitParam(paramType = "query",name = "isReportback",value = "销假识别,默认0",required = true,defaultValue = "0",dataType = "Integer")
    })
    public ResponseEntity<ResultDTO> insertOne(Message message,
                                              @RequestParam(value="file", required=false) MultipartFile file) throws Exception {
        log.info("开始请假");
        String messageId = KeyUtil.getUniqueKey();
        if (StringUtils.isNotBlank(file.getOriginalFilename())) {
            String fileName =  messageId + "-" + file.getOriginalFilename();
            String uploadPath = "/leaveMessage/file";
            String serverUploadPath = "http://"+serverIp+"/file/";
            File realFile = new File(uploadPath);
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realFile, fileName));
            log.info("上传完成");
            message.setFileUrl(serverUploadPath+fileName);
        }else {
            message.setFileUrl("");
        }
        message.setMessageId(messageId);
        message.setCreatTime(new Date());
        log.info("message:{}"+message);
        Message save = messageService.save(message);
        log.info("以保存");
        //return ResultUtil.Success(save);
        return  ResponseEntity.ok().body(ResultUtil.Success(message));
    }

    @PutMapping("/updateMessageById")
    @ApiOperation(value = "按id修改数据")
    //@ApiImplicitParams()
    public ResultDTO updateById(Message message) throws Exception {
        messageService.update(message);
        return ResultUtil.Success(messageService.get(message.getMessageId()));
    }

    //学生获取假条信息
    @GetMapping("/studentGetMessagePages")
    @ApiOperation("按条件查询，分页")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "studentId",value = "学号",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query" , name = "pageNum" , dataType = "Integer" , defaultValue = "1" , required = true, value = "页码"),
            @ApiImplicitParam(paramType = "query" , name = "pageSize" , dataType = "Integer" , defaultValue = "10" , required = false, value = "每页容量")
    })
    public PageList<Message> studentGetMessagePages(Message message, int pageNum, int pageSize)throws Exception{
        return messageService.findPageData(message, pageNum, pageSize,"creat_time DESC");
    }


    //教师获取假条信息
    @GetMapping("/teacherGetMessagePages")
    @ApiOperation("老师查询假条，不分页")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "teacherId",value = "老师教工号号",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query" , name = "pageNum" , dataType = "Integer" , defaultValue = "1" , required = true, value = "页码"),
            @ApiImplicitParam(paramType = "query" , name = "pageSize" , dataType = "Integer" , defaultValue = "10" , required = false, value = "每页容量")
    })
    public ResultDTO teacherGetMessagePages(String teacherId, int pageNum, int pageSize)throws Exception{
        //查询结果
        List<Message> messages = messageService.teacherGetMessage(teacherId);
        //分页
        /*Page<Object> result = PageHelper.startPage(pageNum, pageSize);
        Paginator paginator = new Paginator(pageNum, pageSize, (int) result.getTotal());
        PageList<Message> PageList = new PageList<>(paginator);
        PageList.setData(messages);*/
        return ResultUtil.Success(messages);
    }

    //书记获取假条信息
    @GetMapping("/facultyGetMessagePages")
    @ApiOperation("书记查询假条，不分页")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "facultyUserId",value = "书记教工号",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query" , name = "pageNum" , dataType = "Integer" , defaultValue = "1" , required = true, value = "页码"),
            @ApiImplicitParam(paramType = "query" , name = "pageSize" , dataType = "Integer" , defaultValue = "10" , required = false, value = "每页容量")
    })
    public ResultDTO facultyGetMessagePages(String facultyUserId, int pageNum, int pageSize)throws Exception{
        //查询结果
        List<Message> messages = messageService.facultyGetMessage(facultyUserId);
        /*//分页
        Page<Object> result = PageHelper.startPage(pageNum, pageSize);
        Paginator paginator = new Paginator(pageNum, pageSize, (int) result.getTotal());
        PageList<Message> PageList = new PageList<>(paginator);
        PageList.setData(messages);*/
        return ResultUtil.Success(messages);
    }








   /* @DeleteMapping("/deleteMessageById")
    @ApiOperation("按id删除数据")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", dataType = "Long", required = true, value = "实体类id"),

    })
    public ResultDTO deleteById(@RequestParam(required = true) Long id) throws Exception {
        Message oldMessage = messageService.get(id);
        messageService.deleteById((long) id);
        return ResultUtil.Success(oldMessage);
    }*/

    @GetMapping("/getMessagePages")
    @ApiOperation("按条件查询，分页")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "studentId",value = "学号",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query" , name = "pageNum" , dataType = "Integer" , defaultValue = "1" , required = true, value = "页码"),
            @ApiImplicitParam(paramType = "query" , name = "pageSize" , dataType = "Integer" , defaultValue = "10" , required = false, value = "每页容量")
    })
    public PageList<Message> selectEntityPage(Message message, int pageNum, int pageSize)throws Exception{
        return messageService.findPageData(message, pageNum, pageSize,"creat_time ASC");
    }

    @GetMapping("/getMessageList")
    @ApiOperation("按条件查询，不分页")
    //@ApiImplicitParams()
    public ResultDTO selectEntityPage(Message message)throws Exception{
        return ResultUtil.Success(messageService.findByParams(message,"creat_time DESC"));
    }

    //@CrossOrigin
    @GetMapping("/studentGetMessage")
    @ApiOperation("假条详细")
    @ApiImplicitParam(paramType = "query",name = "messageId",value = "假条编号",required = true,dataType = "String")
    public ResultDTO<MessageDTO> studentGetMessage(String messageId)throws Exception{
        Message message = messageService.get(messageId);

        MessageDTO messageDTO = new MessageDTO(message);


        //补充老师信息
        Teacher teacher = new Teacher();
        teacher.setUserId(message.getTeacherId());
        teacher = teacherService.findByParams(teacher).get(0);
        messageDTO.setTeacherName(teacher.getName());
        messageDTO.setTeacherPhone(teacher.getPhone());
        //补充班级信息
        Student student = new Student();
        student.setUserId(message.getStudentId());
        List<Student> studentList = studentService.findByParams(student);
        Clazz clazz = clazzService.get(studentList.get(0).getClazzId());
        messageDTO.setClassName(clazz.getClazzName());
        //补充学院信息
        Faculty faculty = facultyService.get(clazz.getParentId());
        messageDTO.setFacultyName(faculty.getFacultyName());
        messageDTO.setFacultyTeacher(faculty.getName());
        return ResultUtil.Success(messageDTO);
    }

    @PutMapping("/teacherUpdateMessageById")
    @ApiOperation(value = "老师批改请假条")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "teacherUserId",value = "老师学工号",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "messageId",value = "假条id",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "levelOneComment",value = "老师意见",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "levelOneSign",value = "老师意见标识,同意改为1，不同意改为2",required = true,dataType = "Integer"),
            @ApiImplicitParam(paramType = "query",name = "isReportback",value = "需要销假标识，默认为0，老师觉得需要则改为1",defaultValue = "0",required = false,dataType = "Integer"),
            @ApiImplicitParam(paramType = "query",name = "status",value = "假条标识，后台改")
    })
    public ResultDTO teacherUpdateMessageById(Message message,String teacherUserId) throws Exception {
        Message message1 = messageService.get(message.getMessageId());
        if (!message1.getTeacherId().equals(teacherUserId)) {
            return ResultUtil.Error("500","你不是这个假条的负责人");
        }
        if (message1.getIsLongtime()==0 && message.getLevelOneSign()== 1) {
            message.setStatus("1");
        }else if (message1.getIsLongtime()==0 && message.getLevelOneSign()== 2){
            message.setStatus("2");
        }else if (message1.getIsLongtime()==1 && message.getLevelOneSign()== 2){
            message.setStatus("2");
        }
        message.setLevelOneTime(new Date());
        messageService.update(message);
        return ResultUtil.Success(messageService.get(message.getMessageId()));
    }

    @PutMapping("/faucltyUpdateMessageById")
    @ApiOperation(value = "书记批改请假条")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "facultyUserId",value = "书记学工号",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "messageId",value = "假条id",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "levelTwoComment",value = "书记意见",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "levelTwoSign",value = "书记意见标识,同意改为1，不同意改为2",required = true,dataType = "Integer"),
            @ApiImplicitParam(paramType = "query",name = "status",value = "假条标识，后台改")
    })
    public ResultDTO faucltyUpdateMessageById(Message message,String facultyUserId) throws Exception {
        Message message1 = messageService.get(message.getMessageId());
        Student student = new Student();
        student.setUserId(message1.getStudentId());
        List<Student> studentList = studentService.findByParams(student);
        Clazz clazz = clazzService.get(studentList.get(0).getClazzId());
        Faculty faculty = facultyService.get(clazz.getParentId());



        if (!faculty.getUserId().equals(facultyUserId) ) {
            return ResultUtil.Error("500","你不是这个假条的负责人");
        }
        if (message1.getLevelOneSign() == 2) {
            return ResultUtil.Error("500","该假条已被拒绝");
        }
        if (message1.getIsLongtime() == 0) {
            return ResultUtil.Error("500","改假条不需要书记老师审核");
        }
        if (message1.getIsLongtime()==1 && message.getLevelTwoSign()== 1) {
            message.setStatus("1");
        }
        if (message1.getIsLongtime()==1 && message.getLevelTwoSign()== 2){
            message.setStatus("2");
        }
        message.setLevelTwoTime(new Date());
        messageService.update(message);
        return ResultUtil.Success(messageService.get(message.getMessageId()));
    }

    //同学申请销假
    @PutMapping("/studentReportBack")
    @ApiOperation(value = "同学申请销假")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "student_id",value = "学生学号号",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "reportbackReason",value = "销假理由",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "messageId",value = "假条id",required = true,dataType = "String")
    })
    public ResultDTO studentReportBack(String student_id,String reportbackReason,String messageId) throws Exception {
        Message message = new Message();
        message.setMessageId(messageId);
        List<Message> messageList = messageService.findByParams(message);
        if (messageList.isEmpty()) {
            return  ResultUtil.Error("500","该id对应的假条为空");
        }
        message = messageList.get(0);
        if (!message.getStudentId().equals(student_id) ) {
            return  ResultUtil.Error("500","学生学号不对应");
        }
        message.setStatus("4");
        message.setReportbackSubmitComment(reportbackReason);
        messageService.update(message);
        Message result = new Message();
        result.setMessageId(messageId);
        return ResultUtil.Success(messageService.findByParams(result).get(0));
    }

    @PutMapping("/teacherReportBack")
    @ApiOperation(value = "老师销假")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "teacherUserId",value = "教师教工号",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "messageId",value = "假条Id",required = true,dataType = "String")
    })
    public ResultDTO teacherReportBack(String teacherUserId,String messageId) throws Exception {
        Message message = new Message();
        message.setMessageId(messageId);
        List<Message> messageList = messageService.findByParams(message);
        if (messageList.isEmpty()) {
            return  ResultUtil.Error("500","该id对应的假条为空");
        }
        message = messageList.get(0);
        if (!message.getTeacherId().equals(teacherUserId)) {
            return  ResultUtil.Error("500","这个不是你负责的假条不对应");
        }
        message.setStatus("5");
        messageService.update(message);
        Message result = new Message();
        result.setMessageId(messageId);
        return ResultUtil.Success(messageService.findByParams(result).get(0));
    }
}
